import {IChecker} from "./checker";
import {IQuestionGenner} from "./question_genner";
import {IQuestion} from "../model/question";
import {ReadLine} from "readline";
import * as readline from "readline";

export class Game {

  private checker: IChecker
  private questionGenner: IQuestionGenner
  private rd: ReadLine

  private question: IQuestion = {
    question:""
  }

  constructor(checker: IChecker, questionGenner: IQuestionGenner) {
    this.checker = checker;
    this.questionGenner = questionGenner;
    this.rd = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    })
  }

  public run() {
    // 生成问题
    this.question = this.questionGenner.gen()
    console.log("问题已生成：", this.question)

    // 用户输入
    this.read()

  }

  private check(ans: string) {
    const check = this.checker.check({
      answer: ans,
    }, this.question)

    console.log(check.msg)
    if (!check.isSuccess){
      this.read();
    }else{
      console.log("游戏结束")
      this.rd.close()
    }

  }

  private read() {
    this.rd.question("请输入：", (ans: string) => {
      this.check(ans)
    })
  }
}